/**
 * Created by win 10 on 1/30/2018.
 */
var maxTime;
$.fn.serializeObject = function()
{
    var o = {};
    var a = this.serializeArray();
    $.each(a, function() {
        if (o[this.name] !== undefined) {
            if (!o[this.name].push) {
                o[this.name] = [o[this.name]];
            }
            o[this.name].push(this.value || '');
        } else {
            o[this.name] = this.value || '';
        }
    });
    return o;
};
function GetQueryString(name){
    var reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)");
    var r = window.location.search.substr(1).match(reg);
    if(r!=null)return  unescape(r[2]); return null;
}
$(function () {
    new PCAS("regLocProvince","regLocCity","regLocZone","四川省","成都市","市辖区");
    new PCAS("comLocProvince","comLocCity","comLocZone","四川省","成都市","市辖区");
    /*validate ,paidMoney: {
                isInteger: false
            }*/

    $("#adminSubmission").validate({
        rules: {
            managername: {
                required: true
            },contactTel:{
                required: true,
                isMobile: true
            },fundCount:{
                required: true,
                number:true,
                isInteger: true
            },contactEmail:{
                required: true,
                email:true
            },regLocDetail:{
                required: true
            },comLocDetail:{
                required: true
            },managerMoney: {
                isInteger: true
            },registerMoney: {
                isInteger: true
            }
        },

        message: {
        },
        // debug: true,
        errorElement: "em", //可以用其他标签，记住把样式也对应修改
        success: function(label) {

        },
        submitHandler: function(form) {
            console.log('提交中');
            if($("#admin-info tr").length < 2){
                alert('请至少填写一名高管');
                return false;
            }
            var params = $("#adminSubmission").serializeObject();
            params.stateCapital = parseInt(params.stateCapital);
            params.governmentFund = parseInt(params.governmentFund);
            params.stateHolding = parseInt(params.stateHolding);
            var staffDtoList = [];
            for(var i=1;i<$("#admin-info tr").length;i++){
                var id = $($("#admin-info tr").eq(i)).attr("data-value")
                var aName = $("#admin-info tr").eq(i).find("td").eq(0).text();
                var relation = $("#admin-info tr").eq(i).find("td").eq(2).text();
                var aEmail = $("#admin-info tr").eq(i).find("td").eq(3).text();
                var zhiwu = $("#admin-info tr").eq(i).find("td").eq(1).text();
                staffDtoList.push({"duties":zhiwu,"email":aEmail,"name":aName,"tel":relation,"id" : id});
            }
            params['staffDtoList'] = staffDtoList;
            if (GetQueryString("id")) {
                params['id'] = GetQueryString("id");
            }
            console.log("params::" + JSON.stringify(params));
            $.ajax({
                method: "POST",
                url: "/sichuansfc/fund/manager/update.bs",
                contentType: 'application/json',
                headers: {'FUND_USER_TOKEN': $.cookie('FUND_USER_TOKEN')},
                data:JSON.stringify(params),
                success: function( data ) {
                    console.log(data);
                    if (data.status === 100000) {
                        alert('信息报送成功');
                        location.href = '../html/admin-success.html?id='+data.data
                        // navList();
                    } else {
                        alert(data.msg);
                    }
                }
            });
            return false;
        }
    });

    $("#form-container").validate({
        rules: {
            aName: {
                required: true
            },relation:{
                required: true,
                isMobile: true
            },aEmail:{
                required: true,
                email:true
            }
        },
        errorElement: "em", //可以用其他标签，记住把样式也对应修改
        success: function(label) {

        },
        submitHandler: function(form) {
            console.log('提交中');
            var aName = $("#a-name").val();
            var relation = $("#relation").val();
            var aEmail = $("#a-email").val();
            var zhiwu = [];
            $('input[name="job"]:checked').each(function(){
                zhiwu.push($(this).val());
            });
            if ($(".other-job").val()) {
                zhiwu.push($(".other-job").val());
            }
            zhiwu = zhiwu.join(',');
            if(zhiwu == ''){
                alert("请填写职务");
                return false;
            }

            var str = '<tr class="admin-item">';
            str += '    <td class="add-name">'+aName+'</td>';
            str += '    <td class="add-job">'+zhiwu+'</td>';
            str += '    <td class="add-phone">'+relation+'</td>';
            str += '    <td class="add-email">'+aEmail+'</td>';
            str += '    <td class="delete-admin">删除</td>';
            str += '</tr>';

            $("#admin-info").append(str);
            $(".delete-admin").click(function(){
                if(confirm("确认删除吗?")){
                    $(this).parent().remove();
                }
            });
            $(".close-model").click();
            return false;
        }
    });


    /* 时间插件 */
    var newTime = new Date();
    var y = newTime.getFullYear();
    var m = newTime.getMonth() + 1;
    var d = newTime.getDate();
    maxTime = y+'-'+m+'-'+d;
    $("#setupTime").click(function () {
        $.jeDate('#setupTime',{
            trigger:false,
            minDate: '1990-1-1',
            isTime:true,
            maxDate: maxTime,
            format:'YYYY-MM-DD'
        })
    })
    $("#registerTime").click(function () {
        $.jeDate('#registerTime',{
            trigger:false,
            minDate: '1990-1-1',
            isTime:true,
            maxDate: maxTime,
            format:'YYYY-MM-DD'
        })
    })
    $(".add-admin").click(function () {
        $(".bg-model").css("display",'block');
        $(".model-container1").css("display",'block');
        $("#a-name").val('');
        $("#relation").val('');
        $("#a-email").val('');
        $(".zhiwu input[type=checkbox]").attr('checked',false);
        $(".other-job").val('');
    })
    $(".close-model").click(function () {
        $(".bg-model").css("display",'none');
        $(".model-container1").css("display",'none');
    })
    $(".save-info").click(function(){
        $("#form-container").submit();
    });
    /* 新增管理人 */
    $(".save-info").click(function () {
        var name = $("#a-name").val();
        var relation = $("#relation").val();
        var email = $("#a-email").val()
        var job = ''
        $("input:checkbox[name='job']:checked").each(function() {
            job += $(this).val() + " ";
        });
        job += $(".other-job").val();
    })
    var jsonData;
})
// 手机号码验证
jQuery.validator.addMethod("isMobile", function(value, element) {
    var length = value.length;
    var mobile = /^(13[0-9]{9})|(18[0-9]{9})|(14[0-9]{9})|(17[0-9]{9})|(15[0-9]{9})$/;
    return this.optional(element) || (length == 11 && mobile.test(value));
}, "请正确填写手机号码");
jQuery.validator.addMethod('isInteger', function (value, element) {
    var integer = /^[0-9]\d*$/;
    return this.optional(element) || (integer.test(value));
}, "请输入正整数")

function navList() {
    /* 拉取我的基金管理人信息列表和基金信息列表 */
    $.ajax({
        url: '/sichuansfc/fund/manager/profile.bs',
        type: 'get',
        headers: {'FUND_USER_TOKEN': $.cookie('FUND_USER_TOKEN')},
        success: function (data) {
            if (data.status === 100000) {
                for (var i = 0; i < data.data.length; i++) {
                    if ($(".fund-manager")) {
                        $(".fund-manager").append(
                            '<option value="' + data.data[i].id + '">' + data.data[i].managerName + '</option>'
                        )
                    }
                    if ($(".admin-all")) {
                        $(".admin-all").append(
                            '<li><a href="admin-success.html?id='+data.data[i].id+'">' + data.data[i].managerName + '</a></li>'
                        )
                        for (var j = 0; j < data.data[i].funds.length; j++) {
                            $(".fund-all").append(
                                '<li><a href="fund-success.html?id='+data.data[i].funds[j].id+'">' + data.data[i].funds[j].fundName + '</a></li>'
                            )
                        }
                    }

                }
                location.href = '../html/admin-success.html?id='+data.data[0].id
            }
        }
    })
}